"""
检索elasticsearch 告警
"""


class Alert:
    """
    查询数据
    检查数据告警
    触发告警
    """
    def __init__(self, q, triggers, sample_size=10):
        self.q = q
        self.triggers = triggers
        self.sample_size = sample_size

    def query(self):
        pass

    def convert(self):
        pass

    def check_trigger(self):
        data = self.convert()
        for trigger in self.triggers:
            pass


class CountAlert(Alert):
    """分组"""
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    def convert(self, result):
        count = result['hits']['total']['value']
        return {'count': count}


class GroupAlert:
    """分组告警"""
    def convert(self, result):
        aggregations = result.get('aggregations')
        if not aggregations:
            return None

        buckets = aggregations['1']['buckets']

        # 将聚合结果展开以方便filter识别
        events = []
        for b in buckets:
            e = {k: v['value'] for k, v in b.items() if isinstance(v, dict) and "value" in v}
            e['count'] = b['doc_count']
            e['@key'] = b['key']
            events.append(e)

        return events


class MetricAlert:

    def convert(self, result):
        return {'count': result['hits']['total']['value'],
                **{k: v['value'] for k, v in result.get('aggregations', {}).items()}}


if __name__ == '__main__':
    from common.package.elastic_db import es_db
    es_db.init(hosts='http://192.168.101.79:9200')

    index = 'dsm-1086afd495bd11efae39622bfe3b1ffc'
    raw = {'query': {'match_all': {}}, 'size': 10}
